package com.lcw.library.imagepicker.manager;

import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Build;

import androidx.appcompat.app.AlertDialog;
import androidx.fragment.app.Fragment;

import com.lcw.library.imagepicker.R;
import com.lcw.library.imagepicker.utils.PermissionUtil;

/**
 * 权限管理类
 * 
 * 处理图片选择器的权限申请和权限说明弹窗，包括：
 * - 存储权限检查和申请
 * - 权限说明弹窗显示
 * - 部分权限处理（Android 14+）
 * - 权限被拒绝处理
 * - 更多媒体访问权限请求
 * 
 * 支持Android 6.0-14所有版本的权限处理
 * 
 */
public class PermissionManager {

    private static final int REQUEST_PERMISSION_CODE = 1001;
    private static final int REQUEST_MORE_MEDIA_CODE = 1002;
    
    private Activity activity;
    private Fragment fragment;
    private PermissionCallback callback;
    
    public interface PermissionCallback {
        void onPermissionGranted();
        void onPermissionDenied();
        void onPermissionPartialGranted();
    }
    
    public PermissionManager(Activity activity) {
        this.activity = activity;
    }
    
    public PermissionManager(Fragment fragment) {
        this.fragment = fragment;
        this.activity = fragment.getActivity();
    }
    
    /**
     * 检查并请求权限
     */
    public void checkAndRequestPermission(PermissionCallback callback) {
        this.callback = callback;
        
        if (PermissionUtil.checkStoragePermission(getContext())) {
            // 已有权限
            if (callback != null) {
                callback.onPermissionGranted();
            }
        } else {
            // 需要请求权限，根据配置决定是否显示说明弹窗
            if (ConfigManager.getInstance().isShowPermissionDialog()) {
                showPermissionExplanationDialog();
            } else {
                // 直接请求权限，不显示说明弹窗
                requestPermission();
            }
        }
    }
    
    /**
     * 显示权限说明弹窗
     */
    private void showPermissionExplanationDialog() {
        String title = getContext().getString(R.string.permission_dialog_title);
        String message = getPermissionExplanationMessage();
        
        new AlertDialog.Builder(getContext())
                .setTitle(title)
                .setMessage(message)
                .setPositiveButton(getContext().getString(R.string.permission_dialog_grant), new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        requestPermission();
                    }
                })
                .setNegativeButton(getContext().getString(R.string.permission_dialog_cancel), new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        if (callback != null) {
                            callback.onPermissionDenied();
                        }
                    }
                })
                .setCancelable(false)
                .show();
    }
    
    /**
     * 获取权限说明文本
     */
    private String getPermissionExplanationMessage() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE) {
                // Android 14+
                return getContext().getString(R.string.permission_explanation_android14);
            } else {
                // Android 13
                return getContext().getString(R.string.permission_explanation_android13);
            }
        } else {
            // Android 12及以下
            return getContext().getString(R.string.permission_explanation_legacy);
        }
    }
    
    /**
     * 请求权限
     */
    private void requestPermission() {
        if (fragment != null) {
            PermissionUtil.requestStoragePermission(fragment, REQUEST_PERMISSION_CODE);
        } else {
            // 如果是Activity，需要转换为Fragment来请求权限
            // 这里可以创建一个隐藏的Fragment来处理权限请求
            createPermissionFragment();
        }
    }
    
    /**
     * 创建权限请求Fragment
     */
    private void createPermissionFragment() {
        if (activity instanceof androidx.fragment.app.FragmentActivity) {
            androidx.fragment.app.FragmentActivity fragmentActivity = (androidx.fragment.app.FragmentActivity) activity;
            PermissionFragment permissionFragment = PermissionFragment.newInstance(this);
            fragmentActivity.getSupportFragmentManager()
                    .beginTransaction()
                    .add(permissionFragment, "permission_fragment")
                    .commitAllowingStateLoss();
        }
    }
    
    /**
     * 处理权限请求结果
     */
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        if (requestCode == REQUEST_PERMISSION_CODE) {
            if (PermissionUtil.checkPermissionResult(permissions, grantResults)) {
                if (PermissionUtil.checkStoragePermission(getContext())) {
                    // 完整权限
                    if (callback != null) {
                        callback.onPermissionGranted();
                    }
                } else if (PermissionUtil.hasPartialMediaAccess(getContext())) {
                    // 部分权限
                    showPartialPermissionDialog();
                } else {
                    // 权限被拒绝
                    showPermissionDeniedDialog();
                }
            } else {
                // 权限被拒绝
                showPermissionDeniedDialog();
            }
        }
    }
    
    /**
     * 显示部分权限说明弹窗
     */
    private void showPartialPermissionDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(getContext())
                .setTitle(getContext().getString(R.string.permission_partial_title))
                .setMessage(getContext().getString(R.string.permission_partial_message))
                .setPositiveButton(getContext().getString(R.string.permission_dialog_continue), new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        if (callback != null) {
                            callback.onPermissionPartialGranted();
                        }
                    }
                })
                .setNegativeButton(getContext().getString(R.string.permission_dialog_cancel), new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        if (callback != null) {
                            callback.onPermissionDenied();
                        }
                    }
                });

        // 如果支持请求更多媒体访问，添加"选择更多"按钮
        if (PermissionUtil.canRequestMoreMediaAccess(getContext())) {
            builder.setNeutralButton(getContext().getString(R.string.permission_dialog_select_more), new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    requestMoreMediaAccess();
                }
            });
        }

        builder.show();
    }
    
    /**
     * 显示权限被拒绝弹窗
     */
    private void showPermissionDeniedDialog() {
        new AlertDialog.Builder(getContext())
                .setTitle(getContext().getString(R.string.permission_denied_title))
                .setMessage(getContext().getString(R.string.permission_denied_message))
                .setPositiveButton(getContext().getString(R.string.permission_dialog_settings), new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        PermissionUtil.openAppSettings(getContext());
                        if (callback != null) {
                            callback.onPermissionDenied();
                        }
                    }
                })
                .setNegativeButton(getContext().getString(R.string.permission_dialog_cancel), new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        if (callback != null) {
                            callback.onPermissionDenied();
                        }
                    }
                })
                .show();
    }
    
    /**
     * 获取Context
     */
    private Context getContext() {
        return activity;
    }
    
    /**
     * 请求更多媒体访问权限
     */
    private void requestMoreMediaAccess() {
        if (fragment != null) {
            PermissionUtil.requestMoreMediaAccess(fragment, REQUEST_MORE_MEDIA_CODE);
        } else {
            // 如果是Activity，需要创建Fragment来处理
            createMoreMediaAccessFragment();
        }
    }

    /**
     * 创建更多媒体访问请求Fragment
     */
    private void createMoreMediaAccessFragment() {
        if (activity instanceof androidx.fragment.app.FragmentActivity) {
            androidx.fragment.app.FragmentActivity fragmentActivity = (androidx.fragment.app.FragmentActivity) activity;
            MoreMediaAccessFragment moreMediaAccessFragment = MoreMediaAccessFragment.newInstance(new MoreMediaAccessFragment.MoreMediaAccessCallback() {
                @Override
                public void onMoreMediaAccessResult(boolean success) {
                    if (success) {
                        // 成功获得更多权限
                        if (PermissionUtil.checkStoragePermission(getContext())) {
                            if (callback != null) {
                                callback.onPermissionGranted();
                            }
                        } else if (PermissionUtil.hasPartialMediaAccess(getContext())) {
                            if (callback != null) {
                                callback.onPermissionPartialGranted();
                            }
                        }
                    }
                }
            });
            fragmentActivity.getSupportFragmentManager()
                    .beginTransaction()
                    .add(moreMediaAccessFragment, "more_media_access_fragment")
                    .commitAllowingStateLoss();
        }
    }

    /**
     * 处理更多媒体访问结果
     */
    public void onMoreMediaAccessResult(int requestCode, int resultCode, android.content.Intent data) {
        if (requestCode == REQUEST_MORE_MEDIA_CODE) {
            if (resultCode == Activity.RESULT_OK) {
                // 用户选择了更多媒体文件，重新检查权限
                if (PermissionUtil.checkStoragePermission(getContext())) {
                    if (callback != null) {
                        callback.onPermissionGranted();
                    }
                } else if (PermissionUtil.hasPartialMediaAccess(getContext())) {
                    if (callback != null) {
                        callback.onPermissionPartialGranted();
                    }
                }
            }
        }
    }

    /**
     * 获取权限请求码
     */
    public static int getRequestCode() {
        return REQUEST_PERMISSION_CODE;
    }

    /**
     * 获取更多媒体访问请求码
     */
    public static int getMoreMediaAccessRequestCode() {
        return REQUEST_MORE_MEDIA_CODE;
    }
} 